package com.song.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.song.pojo.User;
import com.song.service.FileStorageService;
import com.song.service.IUserService;
import com.song.util.PatternUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author TonySong
 * @date 2024/6/3 0003
 * @time 10:40
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private FileStorageService fileStorageService;

    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(name = "offset",defaultValue = "1")Integer offset,
                       @RequestParam(name="pagesize",defaultValue = "5")Integer pagesize){
        IPage<User> userIPage = this.userService.pageList(offset, pagesize);

        System.out.println(userIPage.getRecords());
        System.out.println(userIPage.getPages());
        System.out.println(userIPage.getTotal());
        System.out.println(userIPage.getRecords());
        //userIPage.getCurrent()
        model.addAttribute("pager",userIPage);
        //注意页面中通过pager.getTotal()获取总记录数，而不是通过pager.getRecords().size()获取
        //pager.getRecords()获取的是当前页的数据
        return "user/list";
    }

    @GetMapping("/add")
    public synchronized String toadd(){
        return "user/add";
    }

    @PostMapping("/add")
    public String add(@RequestParam("pic") MultipartFile pic, User user) throws IOException {
        //后端通过java的正则验证姓名
        if(!PatternUtil.isChinese(user.getName())){
            System.out.println("姓名格式错误！");
        }else {
            String url = "";
            System.out.println("原始文件名：" + pic.getOriginalFilename());
            System.out.println("文件类型：" + pic.getContentType());

            String originalFilename = pic.getOriginalFilename();

            //上传头像时，需要解决重名的问题：1：UUID 或时间戳  2：保存到不同的路径下
            //1： uuid
//        String newName = UUID.randomUUID().toString()+originalFilename;
            //2：时间戳
//        String newName = new  java.text.SimpleDateFormat("yyyyMMddHHmmss")
//                .format(new java.util.Date())+originalFilename;
            url = this.fileStorageService.uploadImgFile(originalFilename, originalFilename, pic.getInputStream());
            System.out.println(url);
            //设置头像文件名：url
            user.setPhoto(url);
            this.userService.save(user);
        }
        return "redirect:/user/list";

    }

    @GetMapping("/delete/{id}")
    public @ResponseBody boolean delete(@PathVariable("id") int id){
        System.out.println("delete.................");
       return this.userService.removeById(id);

    }


    @GetMapping("/find/{id}")
    public String find(@PathVariable("id") int id,Model model){
        model.addAttribute(this.userService.getById(id));
        return "user/update";
    }

    @PostMapping("/update")
    public String update(User user){
        log.info("update.................{}",user);
        this.userService.saveOrUpdate(user);
        return "redirect:/user/list";
    }

    @GetMapping("/batch_del/{ids}")
    public @ResponseBody boolean bacthDel(@PathVariable("ids") String ids){
        //拆分：1,2,5 --> [1 2 6]
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            this.userService.removeById(Integer.parseInt(id));
        }
        return true;
    }
}
